<?

  error_reporting(E_ALL);
  ini_set('display_errors', 1);

include_once 'controller.inc.php';

$id = $_POST['id'];
$email = $_POST['email'];
$name = $_POST['name'];
$address = $_POST['address'];
$phone = $_POST['phone'];

$db_link = db_connect();

$accept_email = TRUE;

$all_users = db_getAllUsers();
foreach ($all_users as $other_user) {
  if ($other_user->getEmail() == $email && $other_user->getID() != $id) {
    $accept_email = FALSE;
  }
}

if ($accept_email) {
  $user = db_getUser($id);
  
  if ($user->getEmail() == $_COOKIE['user']) {
    $user->setEmail($email);
    $user->setName($name);
    $user->setAddress($address);
    $user->setPhone($phone);
    
    db_updateUser($user);
    setcookie('user', $user->getEmail(), time() + 7200);
    
    $redirect_to = 'dashboard.php?success=Account_updated';
  }
  else {
    $redirect_to = 'dashboard.php?failure=auth';
  }
}
else {
  $redirect_to = 'dashboard.php?failure=email';
}

db_disconnect($db_link);
header('Location: '.$redirect_to);

?>
